import axois from 'axios';
import { MessageBox } from 'element-ui';

import auth from '../util/function';
/* eslint-disable */
const instance = axois.create({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
  transformResponse: [(data) => {
    if (!data) {
      throw new Error('unexpect server error');
    }
    return data;
  }],
});

// inject x-clientInfo & x-token
instance.interceptors.request.use((config) => {
  const ret = {
    ...config,
    headers: {
      ...config.headers,
    },
  };
  return ret;
}, (err) => {
  throw new Error(err);
});

// de
instance.interceptors.response.use((response) => {
  if (response.config.url.indexOf('login') !== -1) {
    const { authorization } = response.headers;
    if (authorization) {
      auth.setToken(authorization);
    }
  }
  if (response.status === 200) {
    if (response.request.responseType === 'blob') {
      return response.data;
    }
    return JSON.parse(response.data);
  }
  if (response.status === 500) {
    MessageBox.message({
      type: 'error',
      message: response.data.message || '后台接口异常，请稍后再试',
    });
  }
  throw new Error('后台数据异常，请稍后再试');
}, () => {
  throw new Error('请求链接有误，请稍后再试');
});

export default instance;
